//
//  NewGoodsDemandViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/7.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HXPhotoPicker

class NewGoodsDemandViewController: BaseViewController {
    @IBOutlet weak var collectionViewheight: NSLayoutConstraint!
    @IBOutlet weak var collection: UICollectionView!
    
    var imageModel = [HXPhotoModel]()
    var imageArray = [UIImage]()
    
    var imgs = [String]()
    
    lazy var manager:HXPhotoManager = {
        var mager = HXPhotoManager.init(type: HXPhotoManagerSelectedType.photo)
        var configuration = HXPhotoConfiguration.init()
        configuration.photoMaxNum = 2
        configuration.openCamera = true
        configuration.movableCropBox = true
        configuration.movableCropBoxEditSize = true
        configuration.requestImageAfterFinishingSelection = true
        mager?.configuration = configuration
        return mager!
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "新品需求"
        setViewStyle()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    // MARK: 提交
    @IBAction func submitButtonClick(_ sender: UIButton) {
        guard self.imageArray.count != 0 else {
            PKhud.showText(text: "请先选择图片~")
            return
        }
        PKhud.show()
        for image in self.imageArray {
            DispatchQueue.global().async {
                self.uploadImage(img: image)
            }
        }
    }
    
    func uploadImage(img:UIImage){
        HttpRequest.uploadImage(image: img) { (result) in
            if result["msg"] as! String == "success"{
                self.imgs.append(result["data"] as! String)
                if self.imgs.count == self.imageArray.count {
                    Utils.dispatchMainQueue {
                        
                        var str = ""
                        for value in self.imgs {
                            str = str + value + ","
                        }
                        let endIndex = str.index(str.startIndex, offsetBy: str.count - 1)
                        str = String(str[..<endIndex])
                        
                        HttpRequest.requestData(.post, URLString: Api.userDemand.rawValue, parameters: ["imgs":str]) { (result) in
                            PKhud.hiden()
                            if result["msg"] as! String == "success"{
                                PKhud.showText(text: "新品需求上传成功~")
                                Utils.DispatchAfter(after: 2, handler: {
                                    self.backBarButtonMethon()
                                })
                            
                            }else{
                                PKhud.showText(text: result["data"] as! String)
                            }
                        }
                    }
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func setViewStyle(){
        self.collection.bounces = false
        self.view.backgroundColor = UIColor.nav_color
        self.collection.backgroundColor = UIColor.nav_color
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize.init(width: (UIScreen.ScreenWidth - 54)/4, height: (UIScreen.ScreenWidth - 54)/4)
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 12, 0, 12)
        flowLayout.minimumInteritemSpacing = 10
        
        self.collection.setCollectionViewLayout(flowLayout, animated: true)
        self.collectionViewheight.constant = (UIScreen.ScreenWidth - 54)/4
    }
}

extension NewGoodsDemandViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.row < self.imageArray.count {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewGoodsImageCollectionViewCell", for: indexPath) as! NewGoodsImageCollectionViewCell
            cell.imageV.image = self.imageArray[indexPath.row]
            cell.deleClosure = { [weak self] in
                self?.imageArray.remove(at: indexPath.row)
                let model = self?.imageModel[indexPath.row]
                self?.imageModel.remove(at: indexPath.row)
                self?.manager.afterSelectedListdeletePhotoModel(model)
                self?.collection.reloadData()
            }
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewGoodsNormalCollectionViewCell", for: indexPath) as! NewGoodsNormalCollectionViewCell
            return cell
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.imageArray.count == 2 {
            return 2
        }else {
            return self.imageArray.count + 1
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.imageArray.count == 2 {
            return
        }
        if indexPath.row == self.imageArray.count {
            
            self.hx_presentAlbumListViewController(with: self.manager, done: { (allList, photoList, videoList, imgArray, original, ctrl) in
                self.navigationController?.navigationBar.isTranslucent = false
                self.imageModel = photoList!
                self.imageArray = imgArray!
                self.collection.reloadData()
            }) { (ctrl) in
                self.navigationController?.navigationBar.isTranslucent = false
            } 
        }
    }
    
    
}

//extension NewGoodsDemandViewController:HXAlbumListViewControllerDelegate{
//    func albumListViewController(_ albumListViewController: HXAlbumListViewController!, didDoneAllImage imageList: [UIImage]!) {
//        self.imageArray = imageList
//        self.collection.reloadData()
//    }
//}




















